package com.usefullc.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.blog.domain.ArticleLike;
import com.usefullc.blog.mapper.ArticleLikeMapper;
import com.usefullc.blog.query.ArticleLikeQuery;
import com.usefullc.blog.vo.ArticleLikeVo;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章点赞服务类
 * @author: 星空
 * @date: 2022-07-12
 */
@Service
public class ArticleLikeService extends AbstractBizService<ArticleLikeMapper, ArticleLike, ArticleLikeQuery> {


    @Override
    protected QueryWrapper<ArticleLike> getQueryWrapper(ArticleLikeQuery query) {
        QueryWrapper<ArticleLike> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<ArticleLikeVo> findVoByPage(ArticleLikeQuery query){
        Pager<ArticleLike> page = this.findByPage(query);
        Pager<ArticleLikeVo> newPage = new Pager<>(page);
        List<ArticleLike> dataList = page.getDataList();
        List<ArticleLikeVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (ArticleLike articleLike : dataList) {
            ArticleLikeVo articleLikeVo = BeanUtils.beanCopy(articleLike, ArticleLikeVo.class);
            newDataList.add(articleLikeVo);
        }
        return newPage;
    }

    public boolean like(Long articleId,Long userId,String ip){
        ArticleLike articleLike = new ArticleLike();
        articleLike.setArticleId(articleId);
        articleLike.setUserId(userId);
        articleLike.setIp(ip);
        articleLike.setStatus(YesNoEnum.YES.getCode());
        try{
            return this.save(articleLike);
        }catch (Exception e){
            //修改
            ArticleLikeQuery articleLikeQuery = new ArticleLikeQuery();
            articleLikeQuery.setArticleId(articleId);
            articleLikeQuery.setUserId(userId);
            ArticleLike entity = this.findOne(articleLikeQuery);
            entity.setStatus(YesNoEnum.YES.getCode());
            return this.update(entity);
        }
    }

    public boolean unLike(Long articleId,Long userId){
        ArticleLikeQuery articleLikeQuery = new ArticleLikeQuery();
        articleLikeQuery.setArticleId(articleId);
        articleLikeQuery.setUserId(userId);
        ArticleLike entity = this.findOne(articleLikeQuery);
        entity.setStatus(YesNoEnum.NO.getCode());
        return this.update(entity);
    }


}
